package com.jiafa.wjxt.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.jiafa.wjxt.vo.ExportProjectResultVO;
import com.jiafa.wjxt.entity.TUserProjectResult;
import com.jiafa.wjxt.mapper.TUserProjectResultMapper;
import com.jiafa.wjxt.service.TUserProjectResultService;

import java.io.IOException;

import com.jiafa.wjxt.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jiafa
 * @since 2021-05-27
 */
@RestController
@RequestMapping("/project/result")
public class TUserProjectResultController {
    @Autowired
    TUserProjectResultService projectResultService;
    @Autowired
    TUserProjectResultMapper tUserProjectResultMapper;

    private String projectKey;

    @PostMapping("/create")
    public void createResult(@RequestBody TUserProjectResult projectResult){
        projectResultService.save(projectResult);
        System.out.println(projectResult);
    }

    @GetMapping("/all")
    public Result queryAllResult(String key){
        // System.out.println(key);
        projectKey = key;
        return projectResultService.queryAllResult(key);
    }

    @GetMapping("/export")
    public void exportResult(String key, HttpServletResponse response) throws IOException {
        ExportProjectResultVO exportProjectResultVO = projectResultService.exportResult(projectKey);
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义标题别名
        exportProjectResultVO.getTitleList().forEach(item -> {
            writer.addHeaderAlias(item.getFieldKey(), item.getTitle());
        });
        //设置每列默认宽度
        writer.setColumnWidth(-1, 20);
        System.out.println(exportProjectResultVO.getResultList());
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(exportProjectResultVO.getResultList(), true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=test.xls");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

}
